/*
 * LiteralImpl.java
 *
 * Created on 21 September 2005.
 */

package org.datamining.guha.model.literal;

import org.datamining.guha.model.Formatter;

/**
 * Default implementation of {@link Literal} interface.
 *
 * @author Lukas Vlcek
 */
public class LiteralImpl implements Literal {
    
    private int symbol;
    private boolean negation;
	private Formatter<Literal> formatter;
    
    /**
     * Literals are created only through LiteralFactory.
     */
    protected LiteralImpl(int symbol, boolean negation) {
        this.symbol = symbol;
        this.negation = negation;
    }
    
    /**
     * Order function:
     * 1) by symbol
     * 2) by negation
     */
    public int compareTo(Literal l) {
        if (symbol < l.getSymbol()) return -1;
        else if (symbol > l.getSymbol()) return 1;
        if (negation == false && l.isNegative() == true) return -1;
        else if (negation == true && l.isNegative() == false) return 1;
        return 0;   
    }
    
    /**
     * Literals are equal if both negation and symbol are equal.
     */
    public boolean equals(Object o) {
        if (o == this) return true;
        if (o == null) return false;
        if (this.getClass() != o.getClass()) return false; 
        Literal l = (Literal)o;
        return (this.negation == l.isNegative() && this.symbol == l.getSymbol());
    }

    /**
     * Taken from J.Bloch's book (Effective Java). 
     */
    public int hashCode() {
        int result = 17;
        result = 37*result + symbol;
        if (negation) result = 37*result + 1;
        return result;
    }
    
    public int getSymbol() {
        return symbol;
    }

    public boolean isNegative() {
        return negation;
    }
    
    /** @return String ouput of formatter */
    public String toString() {
    	if (formatter == null) throw new RuntimeException("Formatter must be set first");
    	return formatter.format(this);
    }

	public void setFormatter(Formatter<Literal> f) {
		formatter = f;
	}

	public Formatter<Literal> getFormatter() {
		return formatter;
	}
}
